package cn.didi.feidi.androidorder.fragment.personal;


import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.xw.repo.XEditText;

import java.util.HashMap;
import java.util.Map;

import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.api.Api;
import cn.didi.feidi.androidorder.api.ApiResponse;
import cn.didi.feidi.androidorder.api.ErrorEvent;
import cn.didi.feidi.androidorder.assembly.CommomDialog;
import cn.didi.feidi.androidorder.core.ActionCallbackListener;
import cn.didi.feidi.androidorder.core.AppActionRequest;
import cn.didi.feidi.androidorder.fragment.FeidiBaseFragment;
import cn.didi.feidi.androidorder.manager.UserManager;
import cn.didi.feidi.androidorder.util.AppUtil;
import cn.didi.feidi.androidorder.util.MD5Util;

public class PersonChangePasswordFragment extends FeidiBaseFragment {

    private static final String TAG = "PersonChangePassword";
    private XEditText oldPasswordEdit;
    private XEditText newPasswordEdit;
    private TextView saveNewPassword;

    /**
     * 与activity关联，后面可考虑单例模式
     *
     * @param bundle
     * @return
     */
    public static PersonChangePasswordFragment newInstance(Bundle bundle) {
        PersonChangePasswordFragment fragment = new PersonChangePasswordFragment();
        if (bundle != null)
            fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View initFragment(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_person_change_password, container, false);
        Log.d(TAG, "initFragment");
        return rootView;
    }

    @Override
    protected void initViews(View rootView) {
        oldPasswordEdit = (XEditText) rootView.findViewById(R.id.person_change_password_old_password_Input_et);
        newPasswordEdit = (XEditText) rootView.findViewById(R.id.person_change_password_new_password_Input_et);
        saveNewPassword = (TextView) rootView.findViewById(R.id.person_change_password_save_new_password_et);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void addListener() {
        saveNewPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //  : 2017/8/8 检测原密码是否正确
                String oldPassword = oldPasswordEdit.getText().toString();
                String newPassword = newPasswordEdit.getText().toString();
                if (oldPassword == null || "".equals(oldPassword)) {
                    makeToast("原密码不能为空");
                } else if (oldPassword.equals(newPassword)) {
                    makeToast("新密码不可与原密码相同");
                } else if (!AppUtil.checkPassword(newPassword)) {
                    makeToast("密码须包含数字和字母");
                } else {
                    setNewPassword(oldPassword, newPassword);
                }
            }
        });
    }

    private void showDialog() {
        //弹出提示框
        CommomDialog dialog = new CommomDialog(getContext(), R.style.dialog, "原密码输入错误", new CommomDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    //  : 2017/8/3 设置飞滴号已设置的标志 并修改
                    oldPasswordEdit.setText("");
                    newPasswordEdit.setText("");
                    Toast.makeText(getContext(), "重新输入", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                }
            }
        }, true, true).setPositiveButton("重新输入", "#43A5F5");
        dialog.show();
    }

    /**
     * 设置密码
     *
     * @param oldPasswordString
     * @param newPasswordString
     */
    private void setNewPassword(String oldPasswordString, String newPasswordString) {
        Map<String, String> params = new HashMap<>();

        params.put("userId", UserManager.getUserId());
        params.put("token", UserManager.getToken());
        params.put("oldPassword", MD5Util.GetMD5Code32Bit(oldPasswordString));
        params.put("newPassword", MD5Util.GetMD5Code32Bit(newPasswordString));

        executeRequest(new AppActionRequest<>(Api.SET_NEW_PASSWORD_BY_OLD_PASSWORD, params,
                new TypeToken<ApiResponse<String>>() {
                }.getType(), new ActionCallbackListener<String>() {
            @Override
            public void onSuccess(String message, String data) {
                Toast.makeText(getContext(), "修改成功", Toast.LENGTH_SHORT).show();

                getFeidiHandler().closeService();
                UserManager.clearBingAccountInfo();
                goLogin();
            }

            @Override
            public void onFailure(int errorEvent, String message) {
                Log.d(TAG, "errorEvent:" + errorEvent + "message=" + message);

                switch (errorEvent) {
                    case ErrorEvent.NONE_USER:
                        //不存在当前用户
                        break;
                    case ErrorEvent.WRONG_PASSWORD:
                        showDialog();
                        break;
                    case ErrorEvent.WRONG_PHONE_NUMBER:
                        makeToast("账号名为手机号");
                        break;
                    case ErrorEvent.PARAM_NULL:
                        makeToast("参数为空");
                        break;
                    case ErrorEvent.PARAM_ILLEGAL:
                        makeToast("参数为空");
                        break;
                    case ErrorEvent.PARAM_ACCESS_FAILURE:
                        makeToast("网络异常，访问失败");
                        break;
                    default:
                        makeToast("未知错误");
                        break;
                }

            }
        }));
    }

    /**
     * 跳转到登录界面，并重启
     */
    private void goLogin() {
        Intent i = getActivity().getPackageManager()
                .getLaunchIntentForPackage(getActivity().getPackageName());
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(i);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

}
